﻿using log4net;
using Mangox.Model.MyBusinessDB;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Mangox.BLL.Stock
{
    public class StockManageBLL
    {
        protected static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static string className = (new StackTrace()).GetFrame(1).GetMethod().ReflectedType.Name + "/";

        public int DeviceTotal(string startTime, string endTime)
        {
            var total = 0;
            DateTime stime = DateTime.Now.Date;
            DateTime etime = DateTime.Now.AddDays(1).Date;
            try
            {
                if (!string.IsNullOrEmpty(startTime))
                {
                    stime = Convert.ToDateTime(startTime);
                }
                if (!string.IsNullOrEmpty(endTime))
                {
                    etime = Convert.ToDateTime(endTime);
                }

                using (MyBusinessDBContext db = new MyBusinessDBContext())
                {
                    total = db.UWP_Device.Where(s => s.CreateTime > stime && s.CreateTime < etime).Count();
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "DeviceTotal fail-{0}", ex);
            }
            return total;
        }

        public int UserActiveTotal(string source,int distinct, string startTime, string endTime)
        {
            var total = 0;
            DateTime stime = DateTime.Now.Date;
            DateTime etime = DateTime.Now.AddDays(1).Date;
            try
            {
                if (!string.IsNullOrEmpty(startTime))
                {
                    stime = Convert.ToDateTime(startTime);
                }
                if (!string.IsNullOrEmpty(endTime))
                {
                    etime = Convert.ToDateTime(endTime);
                }

                using (MyBusinessDBContext db = new MyBusinessDBContext())
                {
                    var obj = db.UserActives.Where(s => s.CreateTime > stime && s.CreateTime < etime);

                    if (!string.IsNullOrEmpty(source))
                    {
                        obj = obj.Where(s => s.Source == source);
                    }
                    if (distinct == 1)
                    {
                        //linq去重复，使用分组GroupBy()
                        total = obj.GroupBy(p => new { p.DevId }).Count();
                    }
                    else
                    {
                        total = obj.Count();
                    }
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "UserActiveTotal fail-{0}", ex);
            }
            return total;
        }
        


    }
}
